var isIE = (document.all) ? true : false;

Array.prototype.contains = function(item){
	  for(i=0;i<this.length;i++){
	  if(this[i]==item){return true;}
	  }
	  return false;
};

Array.prototype.remove = function (obj) {
    return RemoveArray(this,obj);
};

function RemoveArray(array,attachId){
    for(var i=0,n=0;i<array.length;i++)
    {
        if(array[i]!=attachId)
        {
            array[n++]=array[i]
        }
    }
    array.length -= 1;
}

if(!isIE){
    HTMLElement.prototype.__defineGetter__("currentStyle", function () {
        return this.ownerDocument.defaultView.getComputedStyle(this, null);
    });
}

function showEl(el){
	var targetEl = $("#"+el)? $("#"+el):el;
	if(targetEl){
		targetEl.show();
	}
	
}
function hideEl(el){
	var targetEl = $("#"+el)? $("#"+el):el;
	if(targetEl){
		targetEl.hide();
	}
	
}


function HashMap(){  
   /** Map size **/  
   var size = 0;  
   /** object **/  
   var entry = new Object();  
     
   /** put one entry **/  
   this.put = function (key , value)  
   {  
       if(!this.containsKey(key))  
       {  
           size ++ ;  
       }  
       entry[key] = value;  
   }  
     
   /** get one key **/  
   this.get = function (key)  
   {  
       return this.containsKey(key) ? entry[key] : null;  
   }  
     
   /** remove one key **/  
   this.remove = function ( key )  
   {  
       if( this.containsKey(key) && ( delete entry[key] ) )  
       {  
           size --;  
       }  
   }  
     
   /** check if contains Key **/  
   this.containsKey = function ( key )  
   {  
       return (key in entry);  
   }  
     
   /** check if contains Value **/  
   this.containsValue = function ( value )  
   {  
       for(var prop in entry)  
       {  
           if(entry[prop] == value)  
           {  
               return true;  
           }  
       }  
       return false;  
   }  
     
   /** All Value **/  
   this.values = function ()  
   {  
       var values = new Array();  
       for(var prop in entry)  
       {  
           values.push(entry[prop]);  
       }  
       return values;  
   }  
     
   /** all Key **/  
   this.keys = function ()  
   {  
       var keys = new Array();  
       for(var prop in entry)  
       {  
           keys.push(prop);  
       }  
       return keys;  
   }  
     
   /** Map Size **/  
   this.size = function ()  
   {  
       return size;  
   }  
     
   /* clear */  
   this.clear = function ()  
   {  
       size = 0;  
       entry = new Object();  
   }  
}


function FadeElement(elItem){
	this.item = elItem;
	this.styleAttr = "opacity";
	this.minValue = 0;
	this.maxValue = 1;
	this.step = 0.01;
	this.currentStay = 0;
	this.fade = function(){
		var oldOpacity = this.getOpacity();
		var newOpacity = parseFloat(oldOpacity)+this.step;
		if(newOpacity>this.maxValue){
			if(this.currentStay > 20){
				this.currentStay = 0;
				this.step = -0.01;
			}else{
				this.currentStay = this.currentStay+1;
			}
		}else if(newOpacity < this.minValue){
			if(this.currentStay > 20){
				this.currentStay = 0;
				this.step = 0.01;
			}else{
				this.currentStay = this.currentStay+1;
			}
		}else{
			this.setOpacity(newOpacity);
		}
	};
	this.getOpacity = function(){
		return this.item.currentStyle.opacity;
	};
	this.setOpacity = function(value){
		this.item.style.opacity = value;
	};
	this.setOpacity(Math.random());
}

var opacitycControler = {
	fadeElements:[],	
	push:function(elItem){
		this.fadeElements.push(new FadeElement(elItem));
	},
	run:function(){
		for ( var int = 0; int < this.fadeElements.length; int++) {
			var fadeElement = this.fadeElements[int];
			fadeElement.fade();
		}
	}
		
};
setInterval(function(){opacitycControler.run();}, 20);


var LoingManager = {
		xmlHttp:null,
		login:function (){
			var url = "/getOauthAuthriseUrl.action?";
			if(this.ajaxRequest(url)) {
				var oauthriseUrl = this.xmlHttp.getResponseHeader('authriseUrl');
				window.location.href = oauthriseUrl;
		    }
		},
		
		ajaxRequest:function (url){
			  if(window.XMLHttpRequest){
				  this.xmlHttp=new XMLHttpRequest();
			  } else if(window.ActiveXObject) {
				  this.xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			  } else {
				  return;
			  }
			  //xmlHttp.onreadystatechange = handleInventoryId;
			  this.xmlHttp.open('GET',url,false);
			  this.xmlHttp.send(null);  
			  if (this.xmlHttp.readyState == 4 && this.xmlHttp.status == 200) {
			    return true;
			  } else {
			    return false;
			  }
		}
};


var PrizeDisplayer = {
		canvas:"",
		counter:0,
		timer:null,
		prize:null,
		start:function(){
			PrizeDisplayer.timer = setInterval(function() {
				var canvasElmt = document.getElementById(PrizeDisplayer.canvas);
				if(PrizeDisplayer.counter==PrizeDisplayer.prize.length){
					clearInterval(PrizeDisplayer.timer);
					canvasElmt.innerHTML = "xxx已经一贫如洗了...";
				}else{
					canvasElmt.innerHTML = "成功偷盗金币 "+PrizeDisplayer.prize[PrizeDisplayer.counter]+" 枚 !";
					PrizeDisplayer.counter++;
				}
			},3000);
		}
};
var cubicData = [
                 {type:"diamon", img:"/img/success.jpg", actionType:"getDiamon", count:"14"},
                 {type:"fail", img:"/img/fail.jpg", actionType:"getNothing", count:"50"}
                 
                 ];
function Cubic(type, img, actionType, cubicDiv){
	this.id = "";
	this.type = type;
	this.img = img;
	this.actionType = actionType;
	this.div = cubicDiv;
	this.setImg=  function(){
		var img = document.createElement("Img");
		img.src = this.img;
		img.style.width = "40px";
		img.style.height = "40px";
		this.div.appendChild(img);
	};
	this.cleanDiv = function(){
		this.div.innerHTML = "";
	};	
	
	this.get = function(){
		this.setImg();
		var fn = fnMgr[this.actionType];
		if(typeof fn=='function'){
			fnMgr[this.actionType]();
		}
	};
	this.setImg();
}

var fnMgr={
		_diamonMgr:{
			 	diamonsInPackage:0,	
				getDiamon:function(){
					this.diamonsInPackage = this.diamonsInPackage+1;
					$("#moneyInPkg").html(this.diamonsInPackage);
				},
				done:function(){
					$("#moneyGotId").html(this.diamonsInPackage);
				}
		},
		getDiamon:function(){
			this._diamonMgr.getDiamon();
		},
		done:function(){
			this._diamonMgr.done();
		}
	};

var cubicMgr = {
		_cubicMap:new HashMap(),
		_generateId:function(index){
			return "cubicId"+index;
		},
		put:function(cubic, index){
			var id = this._generateId(index);
			cubic.id = id;
			this._cubicMap.put(id, cubic);
		},
		getById:function(id){
			return this._cubicMap.get(id);
		},
		getRandomCubicList:function(){
			return this._cubicMap.values().sort((function(){return Math.random()>0.5?-1:1;}));
		},
		onclick:function(id){
			var target = this._cubicMap.get(id);
			if(target){
				target.get();
			}
		}
	};

var gameMgr = {
	pbarWidthPercent:100,
	finish:false,
	positionId:"cubicContainer",
	init:function(cubicData){
		var index = 0;	
		for ( var int = 0; int < cubicData.length; int++) {
			var count = cubicData[int].count;
			for ( var int2 = 0; int2 < count; int2++) {
				var cubicDiv = this._createCubic(cubicData[int].img);
				var cubic = new Cubic(cubicData[int].type, cubicData[int].img, cubicData[int].actionType, cubicDiv);
				index++;
				cubicMgr.put(cubic, index);
			}
		}
	},
	_createCubic:function(imgUrl){
		var div = document.createElement("div");
		setClass(div, 'cubic');
		return div;
	},
	
	showInfoBeforeStart:function(button){
		if(button){
			button.style.display="none";
		}
		var cubicList = cubicMgr.getRandomCubicList();
		for ( var int = 0; int < cubicList.length; int++) {
			$("#"+this.positionId).append(cubicList[int].div);
		}
		var rows = Math.sqrt(cubicList.length);
		$("#gameTable").css("width", (40*rows+30)+"px");
		$("#gameTable").css("height", (40*rows+30)+"px");
		$("#gameTable").css("display", "");
		setTimeout(function(){gameMgr.startGame();}, 3000);
	},
	startGame:function(){
		var self=this;
		var cubicList = cubicMgr.getRandomCubicList();
		for ( var int = 0; int < cubicList.length; int++) {
			var target = cubicList[int];
			target.cleanDiv();
			$(target.div).attr('onclick', "cubicMgr.onclick('"+target.id+"');");
		}
		showEl("gameTable");
		showEl("doneBtn");
		hideEl("goBtn");
		setTimeout(self.countTime,500);
	},
	countTime:function(){
		gameMgr.pbarWidthPercent = gameMgr.pbarWidthPercent-1;
		$("#runningPbar").css("width", gameMgr.pbarWidthPercent+"%");
		if(gameMgr.pbarWidthPercent>0 && !gameMgr.finish ){
			window.setTimeout(gameMgr.countTime,100);
		}else if( !gameMgr.finish ){
			hideEl("doneBtn");
			hideEl("gameTable");
			showEl("stealFail");
		}
	},
	done:function(actionId){
		hideEl("doneBtn");
		hideEl("gameTable");
		showEl("stealSuccess");
		fnMgr.done();
		this.finish = true;
	}
};




function setClass(el, className){
	if(isIE){
		el.className=className;
	}else{
		el.setAttribute("class", className);
	}
}
gameMgr.init(cubicData);




